import { getList } from "@/api/content";
import Top from "@/components/contest/Top";

export default {
  name: "list",
  data() {
    return {
      current: "",
      isEnd: false,
      isRepeat: false,
      status: "",
      tag: "",
      sort: "created",
      page: 0,
      catalog: "",
      limit: 5,
      catalog: "",
      lists: [],
      isRepeat: false,
    };
  },
  components: {
    Top,
  },
  mounted() {
    let catalog = this.$route.params["catalog"];
    if (typeof catalog !== "undefined" && catalog !== "") {
      this.catalog = catalog;
    }
    this._getLists();
  },
  watch: {
    current(newval, oldval) {
      // console.log('current:' + oldval + ','+newval);
      this.init();
    },
    $route(newval, oldval) {
      let catalog = this.$route.params["catalog"];
      if (typeof catalog !== "undefined" && catalog !== "") {
        this.catalog = catalog;
      }
      this.init();
    },
  },
  methods: {
    init() {
      this.page = 0;
      this.lists = [];
      this.isEnd = false;
      this._getLists();
    },
    nextPage() {
      this.page++;
      this._getLists();
    },
    search(val) {
      if (typeof val === "undefined" && this.current === "") {
        return;
      }
      this.current = val;
      // console.log(val);
      switch (val) {
        case 0:
          this.status = "0";
          this.tag = "";
          break;
        case 1:
          this.status = "1";
          this.tag = "";
          break;
        case 2:
          this.status = "";
          this.tag = "精华";
          break;
        case 3:
          this.sort = "created";
          break;
        case 4:
          this.sort = "answer";
          break;
        default:
          this.status = "";
          this.tag = "";
          this.current = "";
      }
    },
    _getLists() {
      if (this.isRepeat) return;
      if (this.isEnd) return;
      this.isRepeat = true;
      let options = {
        catalog: this.catalog,
        isTop: 1,
        page: this.page,
        limit: this.limit,
        sort: this.sort,
        tag: this.tag,
        status: this.status,
        // lists: this.lists
      };
      getList(options)
        .then((res) => {
          //加锁防止用户多次点击
          this.isRepeat = false;
          if (res.code === 200) {
            // console.log(res.data);
            if (res.data.length < this.limit) {
              this.isEnd = true;
            }
            if (this.lists.length === 0) {
              this.lists = res.data;
            } else {
              this.lists = this.lists.concat(res.data);
            }
          }
        })
        .catch((err) => {
          console.log(err);
          this.isRepeat = false;
          if (err) {
            console.log(err);
            this.$alert(err.message);
          }
        });
    },
  },
};
